package com.ilock.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import sun.misc.BASE64Encoder;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
/**
 * 
 * @author ProMoriarty
 * @version 1.0
 * @time 2017-05-10 23:09:00
 */
public class CodeGenerator implements ICodeGenerator{

	/**
	 * get six bits numeric random code
	 * @return random code
	 */
	public String getRandomCode(){
		return RandomStringUtils.randomNumeric(6);		
	}
	
	
	/**
	 * encoding the string to get a access token
	 * @param str the string need to be encoding
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public String MD5Encoding(String str)throws NoSuchAlgorithmException, UnsupportedEncodingException{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		MessageDigest md5 = MessageDigest.getInstance("md5");
		Random r = new Random();
		//return new String(md5.digest((str+df.format(new Date()).toString()).getBytes()));
		if(str.length()>32){
			str=str.substring(0,32);
		}
		String data = r.nextDouble()+str+df.format(new Date()).toString();
		String returndata  =new String(Base64.encodeBase64(data.getBytes()));
		returndata = returndata.replace("=","ASD");
		returndata = returndata.replace("/","LLD");
		returndata = returndata.replace("+","3234");
		return returndata;
	}

}
